package com.LGF.Book.action;

import com.LGF.Book.bean.Book;
import com.LGF.Book.bean.BookType;
import com.LGF.Book.biz.BookBiz;
import com.LGF.Book.biz.BookTypeBiz;
import com.LGF.Book.util.DateHelper;
import com.alibaba.fastjson.JSONObject;
import com.mchange.v1.identicator.IdList;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet("/book.let")
public class BookServlet extends HttpServlet {

    //创建BookBiz对象
    BookBiz bookBiz = new BookBiz();
    //创建BookTypeBiz对象
    BookTypeBiz bookTypeBiz = new BookTypeBiz();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * /book.let?type=query //分页查询所有图书信息
     * /book.let?type=addpre //添加图书信息准备
     * /book.let?type=add //添加图书信息
     * /book.let?type=modifypre&id=xx //修改图书信息前准备
     * /book.let?type=modify&id=xx //修改图书信息
     * /book.let?type=remove&id=xx //删除图书信息
     * /book.let?type=select //按条件模糊查询图书信息
     * /book.let?type=detail&id=xx //查看图书信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //创建输出流对象,打印信息
        PrintWriter out = resp.getWriter();

        //创建session对象
        HttpSession session = req.getSession();
        String type = req.getParameter("type");

        //判断接收类型
        switch (type){
            case "query":
                query(req,resp,out);
                break;
            case"addpre":
                addpre(req,resp,out);
                break;
            case "add":
                try {
                    add(req, resp, out);
                } catch (FileUploadException e) {
                    e.printStackTrace();
                    //resp.sendError(500, "文件上传失败");
                } catch (Exception e) {
                    e.printStackTrace();
                    resp.sendError(500, e.getMessage());
                }
                break;
            case "modifypre":
                modifypre(req,resp,out);
                break;
            case "modify":
                try {
                    modify(req,resp,out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case "remove":
                remove(req,resp,out);
                break;
            case "select":
                select(req,resp,out);
                break;
            case"doajax":
                doajax(req,resp,out);
                break;
            case "detail":
                detail(req,resp,out);
                break;
        }

    }

    /**
     * 实现查看图书信息功能
     * @param req
     * @param resp
     * @param out
     */
    private void detail(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //接收前端传过来的图书id值
        long bookId = Long.parseLong(req.getParameter("id"));
        //调用biz层 根据图书id查询图书信息
        Book book = bookBiz.getById(bookId);

        //调用BookTypebiz层获取所有图书类型
        List<BookType> bookTypes = bookTypeBiz.getAll();
        if (book!=null){

            HttpSession session = req.getSession();
            //将信息存入session中
            session.setAttribute("book",book);
            session.setAttribute("bookType",bookTypes);
            //转发
            req.getRequestDispatcher("book_detail.jsp").forward(req,resp);
        }
        else{
            out.println("<script>alert('信息有误');location.href='user_Main.jsp';</script>");
        }

//        //存到session对象中
//        HttpSession session =req.getSession();
//        session.setAttribute("book",book);
//        //转发
//        req.getRequestDispatcher("detail.jsp");

    }

    /**
     * 利用adjax传递
     * @param req
     * @param resp
     * @param out
     */
    private void doajax(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {



    }

    /**
     * 添加图书前准备
     * @param req
     * @param resp
     * @param out
     */
    private void addpre(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //调用biz层获取所有的图书类别
        List<BookType> bookTypes = bookTypeBiz.getAll();

        //存储信息到session中
        req.setAttribute("bookTypes",bookTypes);
        //转发
        req.getRequestDispatcher("book_add.jsp").forward(req,resp);

    }

    /**
     * 实现条件查询图书信息功能
     * @param req
     * @param resp
     * @param out
     */
    private void select(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {

        //获取前端传递过来的searchType值

        String searchType = req.getParameter("searchType");
        //根据selectType的值判断查询条件
        if (searchType.equals("bookId")){
            //获取前端传递过来的search值
            String search = req.getParameter("search");
            //调用biz层根据id模糊查询图书信息
            List<Book> books = bookBiz.selectById(search);

            //创建JSONObject对象
            JSONObject json = new JSONObject();
            json.put("data",books);
            json.put("code",0);
            json.put("count",books.size());

            //打印
            out.print(json);
        } else if(searchType.equals("bname")){
            //获取前端传递过来的search值
            String search = req.getParameter("search");
            //调用biz层根据id模糊查询图书信息
            List<Book> books = bookBiz.selectByBname(search);

            //创建JSONObject对象
            JSONObject json = new JSONObject();
            json.put("data",books);
            json.put("code",0);
            json.put("count",books.size());

            //打印
            out.print(json);
        }else if(searchType.equals("bookType")){
            //获取前端传递过来的search值
            String search = req.getParameter("search");
            //调用BookType biz层模糊查询图书类型名获取图书类型集合
//            List<BookType> bookTypes = bookTypeBiz.selectTName(search);
//
//            List<Book> books = new ArrayList<>();
//
//            for(BookType bookType :bookTypes){
//                Book book = bookBiz.getBytypeId(bookTypeBiz.getById().getId());
//            }

            //调用bookBiz层中根据类型名称获取图书信息
            List<Book> data = bookBiz.selectByType(search);

            // List<Map<String, Object>> data = bookBiz.selectTname(search);

            //创建JSONObject对象
            JSONObject json = new JSONObject();
            json.put("data",data);
            json.put("code",0);
            json.put("count",data.size());

            //打印
            out.print(json);
        }

    }

    /**
     * 实现删除图书功能
     * @param req
     * @param resp
     * @param out
     */
    private void remove(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //获取前端传过来的ID值
        long id = Long.parseLong(req.getParameter("id"));
        //调用biz层根据id删除图书信息
        int count = bookBiz.remove(id);
        //判断是否删除成功
        if (count>0){
            out.println("<script>alert('图书信息删除成功！');location.href='book_list.jsp';</script>");
        }
        else{
            out.println("<script>alert('图书信息删除失败！');location.href='book_list.jsp';</script>");
        }

    }

    /**
     * 实现修改图书功能
     * @param req
     * @param resp
     * @param out
     */
    private void modify(HttpServletRequest req, HttpServletResponse resp, PrintWriter out)throws Exception {
//        //接收前端所有要修改的值
//        long bookId = Long.parseLong(req.getParameter("id"));
//        String bname = req.getParameter("bname");
//        long typeId = Long.parseLong(req.getParameter("bookType"));
//        float price = Float.parseFloat(req.getParameter("price"));
//        String desc = req.getParameter("desc");
//        String pic = req.getParameter("pic");
//        String publish = req.getParameter("publish");
//        long stock = Long.parseLong(req.getParameter("stock"));
//        String address = req.getParameter("address");
//        String author = req.getParameter("author");
//        //调用biz层修改图书信息
//        int count = bookBiz.modify(bookId, typeId, bname, price, desc, pic, publish, author, stock, address);
//        //判断是否修改成功
//        if (count>0){
//            out.println("<script>alert('图书信息修改成功！');location.href='admin_Main.jsp';</script>");
//        }
//        else{
//            out.println("<script>alert('图书信息修改失败！');location.href='admin_Main.jsp';</script>");
//        }
        //1.构建磁盘工厂对象，存储文件
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //1.1 设置大小
        factory.setSizeThreshold(1024 * 9);
        //1.2 临时存放位置
        File file = new File("D:\\IdeaProjects\\Books\\temp");
        if (!file.exists()) {
            file.mkdirs();//创建文件夹
        }
        factory.setRepository(file);//设置成仓库

        //2.文件上传+表单数据
        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        //3.将请求解析成一个个FileItem（文件+表单元素）
        List<FileItem> fileItems = fileUpload.parseRequest(req);

        //4.遍历FileItem
        Book book = new Book();
        for (FileItem item : fileItems) {
            if (item.isFormField()) {
                //4.1 元素名称和用户填写的值 name ：文城
                String name = item.getFieldName();
                String value = item.getString("utf-8"); //防止乱码
                System.out.println(name+":"+value);
                switch (name) {
                    case "bname":
                        book.setBname(value);
                        break;
                    case "typeId":
                        book.setTypeId(Long.parseLong(value));
                        break;
                    case "author":
                        book.setAuthor(value);
                        break;
                    case "price":
                        book.setPrice(Float.parseFloat(value));
                        break;
                    case "pic":
                        book.setPic(value);
                        break;
                    case "publish":
                        book.setPublish(value);
                        break;
                    case "stock":
                        book.setStock(Long.parseLong(value));
                        break;
                    case "address":
                        book.setAddress(value);
                        break;
                    case "desc":
                        book.setDesc(value);
                        break;
                }
            } else {
                //4.2 文件：图片的文件名  文城.png
                String fileName = item.getName();

                //避免文件替换：用DateHelper类生成当前系统时间 填写图片名：当前系统时间.png
                if (fileName.trim().length() > 0) {
                    //4.2.1 获取后缀名 .png
                    String filterName = fileName.substring(fileName.lastIndexOf("."));
                    //4.2.2 修改文件名
                    fileName = DateHelper.getImageName() + filterName;

                    //图片保存在哪里？ idea 映射 保存在out文件夹中，Eclipse 直接复制项目文件保存在tomcat webapps夹中
                    //虚拟路径：Image/cover/1-1.png
                    //文件的读写路径：是实际路径
                    String path = req.getServletContext().getRealPath("lib/Images/cover");
                    //路径为 202203221438.png
                    String filePath = path + "/" + fileName;
                    //数据库表中的路径：Images/cover/101-1.png：是相对项目的根目录的位置
                    String dbPath = "lib/Images/cover/" + fileName;

                    book.setPic(dbPath);

                    //4.3 保存文件
                    item.write(new File(filePath));

                }

            }



        }
        //接收前端传过来的id值
        long id = Long.parseLong(req.getParameter("id"));
        book.setId(id);

        System.out.println(book.toString());
        //5.将信息保存到数据库
        int count = bookBiz.modify(book);
        System.out.println(count);
        if (count > 0) {
            out.println("<script>alert('修改书籍成功');location.href='book_list.jsp';</script>");
        } else {
            out.println("<script>alert('修改书籍失败');location.href='book_add.jsp';</script>");

        }
    }

    /**
     * 修改前准备
     * @param req
     * @param resp
     * @param out
     */
    private void modifypre(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
        //接收前端传过来的id值
        long bookId = Long.parseLong(req.getParameter("id"));
        //调用biz层根据id获取图书信息
        Book book = bookBiz.getById(bookId);
        //调用BookTypebiz层获取所有图书类型
        List<BookType> bookTypes = bookTypeBiz.getAll();
        if (book!=null){

            HttpSession session = req.getSession();
            //将信息存入session中
            session.setAttribute("book",book);
            session.setAttribute("bookType",bookTypes);
            //转发
            req.getRequestDispatcher("book_modify.jsp").forward(req,resp);
        }
        else{
            out.println("<script>alert('信息有误');location.href='amdin_Main.jsp';</script>");

        }

    }

    /**
     * 实现添加图书功能
     * @param req
     * @param resp
     * @param out
     */
    private void add(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws Exception {
        //1.构建磁盘工厂对象，存储文件
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //1.1 设置大小
        factory.setSizeThreshold(1024*9);
        //1.2 临时存放位置
        File file = new File("D:\\IdeaProjects\\Books\\temp");
        if (!file.exists()){
            file.mkdirs();//创建文件夹
        }
        factory.setRepository(file);//设置成仓库

        //2.文件上传+表单数据
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //System.out.println(fileUpload.toString());

        //3.将请求解析成一个个FileItem（文件+表单元素）
        List<FileItem> fileItems  = fileUpload.parseRequest(req);
        //System.out.println(fileItems.toString());

        //4.遍历FileItem
        Book book = new Book();
        for (FileItem item : fileItems) {
            if (item.isFormField()){
                //4.1 元素名称和用户填写的值 name ：文城
                String name = item.getFieldName();
                System.out.println(name);
                String  value = item.getString("utf-8"); //防止乱码
                switch (name){
                    case "id":
                        book.setId(Long.parseLong(value));
                        break;
                    case "bname":
                        book.setBname(value);
                        break;
                    case "typeId":
                        book.setTypeId(Long.parseLong(value));
                        break;
                    case "author":
                        book.setAuthor(value);
                        break;
                    case "price":
                        book.setPrice(Float.parseFloat(value));
                        break;
                    case "pic":
                        book.setPic(value);
                        break;
                    case "publish":
                        book.setPublish(value);
                        break;
                    case "stock":
                        book.setStock(Long.parseLong(value));
                        break;
                    case "address":
                        book.setAddress(value);
                        break;
                    case "desc":
                        book.setDesc(value);
                        break;

                }
            }
            else{
                //4.2 文件：图片的文件名  文城.png
                String fileName = item.getName();

                //避免文件替换：用DateHelper类生成当前系统时间 填写图片名：当前系统时间.png
                if (fileName.trim().length()>0){
                    //4.2.1 获取后缀名 .png
                    String filterName = fileName.substring(fileName.lastIndexOf("."));
                    //4.2.2 修改文件名
                    fileName = DateHelper.getImageName()+filterName;

                    //图片保存在哪里？ idea 映射 保存在out文件夹中，Eclipse 直接复制项目文件保存在tomcat webapps夹中
                    //虚拟路径：Image/cover/1-1.png
                    //文件的读写路径：是实际路径
                    String path = req.getServletContext().getRealPath("/lib/Images/cover");
                    //路径为 202203221438.png
                    String filePath = path+"/"+fileName;
                    //数据库表中的路径：Images/cover/101-1.png：是相对项目的根目录的位置
                    String dbPath = "lib/Images/cover/"+fileName;

                    book.setPic(dbPath);

                    //4.3 保存文件
                    item.write(new File(filePath));

                }

            }

        }

        //5.将信息保存到数据库
        int count = bookBiz.add(book);
        if (count>0){
            out.println("<script>alert('添加书籍成功');location.href='book_list.jsp';</script>");
        }else {
            out.println("<script>alert('添加书籍失败');location.href='book_add.jsp';</script>");

        }

    }

    /**
     * 实现分页查询图书信息功能
     * @param req
     * @param resp
     * @param out
     */
    private void query(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) {
        //调用biz层获取所有图书信息方法
        List<Book> all = bookBiz.getAll();
        //接收前端传过来的page和limit值
        int page = Integer.parseInt(req.getParameter("page"));
        int limit = Integer.parseInt(req.getParameter("limit"));


        int pageIndex=(page-1)*limit;
        //调用biz层分页查询图书信息方法
        List<Book> bookList = bookBiz.getPage(pageIndex, limit);
        System.out.println(bookList);
        //创建JSONObject对象
        JSONObject json = new JSONObject();
        json.put("data",bookList);
        json.put("code",0);
        json.put("count",all.size());

        //打印
        out.print(json);

    }
}
